import 'package:bot_toast/bot_toast.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_chip/bean/User.dart';
import 'package:flutter_chip/config/Api.dart';
import 'package:flutter_chip/config/Http.dart';
import 'package:flutter_chip/config/Routers.dart';
import 'package:flutter_chip/utils/toast_utils.dart';
import 'package:flutter_chip/widget/keyboard/view_keyboard.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:fsuper/fsuper.dart';
import 'package:provide/provide.dart';

///提现
class TakeCashPage extends StatefulWidget {
  final String totalMoney;

  const TakeCashPage({Key key, this.totalMoney}) : super(key: key);

  @override
  _TakeCashPageState createState() => _TakeCashPageState();
}

class _TakeCashPageState extends State<TakeCashPage> {
  TextEditingController _moneyController = TextEditingController();
  Color borderColor = Color(0xffFFC66D);
  Color bgColor = Color(0x7fFFC66D);
  String payType = "-1";
  bool btnEnable = false;
  bool showKeyboard = false;
  User user;

  @override
  void initState() {
    super.initState();
    if (double.parse(widget.totalMoney) > 0) {
      btnEnable = true;
    }
  }

  @override
  Widget build(BuildContext context) {
    user = Provide.value<User>(context);
    return Scaffold(
      backgroundColor: Color(0XFFEDEDED),
      appBar: AppBar(
        backgroundColor: Theme.of(context).canvasColor,
        title: Text("提现", style: TextStyle(fontSize: 18)),
        centerTitle: true,
      ),
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            dirWidget(),
            inputArea(),
            descWidget(),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    _moneyController.dispose();
  }

  ///提现到
  Widget dirWidget() {
    return Container(
      padding: EdgeInsets.only(top: 20, left: 20, right: 20, bottom: 10),
      margin: EdgeInsets.only(left: 10, right: 10, top: 20, bottom: 0),
      decoration: BoxDecoration(
        color: Color(0xffF7F7F7),
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(6),
          topRight: Radius.circular(6),
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            "提现到：",
            style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
          ),
          Container(
            child: FSuper(
              onClick: () {
                setState(() {
                  payType = "01";
                });
              },
              height: 48,
              width: double.infinity,
              padding: EdgeInsets.only(left: 40, right: 20),
              textAlignment: Alignment.centerLeft,
              text: "支付宝",
              textSize: 16,
              child1: Icon(
                FontAwesomeIcons.alipay,
                size: 28,
                color: Color(0XFF00A1E9),
              ),
              child1Alignment: Alignment.centerLeft,
              child2: Icon(
                payType == '01'
                    ? Icons.check_box
                    : Icons.check_box_outline_blank,
                color: borderColor,
              ),
              child2Alignment: Alignment.centerRight,
            ),
          ),
          Container(
            height: 0.5,
            width: double.infinity,
            color: Theme.of(context).dividerColor,
          ),
          Container(
            child: FSuper(
              onClick: () {
                setState(() {
                  payType = "02";
                });
              },
              height: 48,
              width: double.infinity,
              padding: EdgeInsets.only(left: 40, right: 20),
              textAlignment: Alignment.centerLeft,
              text: "微信",
              textSize: 16,
              child1: Icon(
                FontAwesomeIcons.weixin,
                size: 28,
                color: Color(0XFF01D00E),
              ),
              child1Alignment: Alignment.centerLeft,
              child2: Icon(
                payType == '02'
                    ? Icons.check_box
                    : Icons.check_box_outline_blank,
                color: borderColor,
              ),
              child2Alignment: Alignment.centerRight,
            ),
          ),
        ],
      ),
    );
  }

  ///金额输入区
  Widget inputArea() {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.only(top: 20, left: 20, right: 20, bottom: 10),
      margin: EdgeInsets.only(left: 10, right: 10, top: 0),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          bottomLeft: Radius.circular(6),
          bottomRight: Radius.circular(6),
        ),
      ),
      child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text('提现金额', style: TextStyle(fontWeight: FontWeight.w600)),
            SizedBox(height: 10),
            FSuper(
              width: double.infinity,
              text: "￥",
              textAlignment: Alignment.centerLeft,
              textSize: 24,
              textWeight: FontWeight.w900,
              child1: TextField(
                controller: _moneyController,
                style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
                keyboardType: TextInputType.numberWithOptions(decimal: true),
                textInputAction: TextInputAction.done,
                decoration: InputDecoration(
                  contentPadding: EdgeInsets.all(10),
                  border: OutlineInputBorder(borderSide: BorderSide.none),
                  hintText: "可转出${widget.totalMoney}元",
                  hintStyle: TextStyle(color: Color(0xffdddddd), fontSize: 18),
                ),
              ),
              child1Alignment: Alignment.centerLeft,
              child1Margin: EdgeInsets.only(left: 20, bottom: 2, top: 6),
            ),
            Divider(color: Color(0xffE2E2E2), height: 10, thickness: 1),
            FSuper(
              width: double.infinity,
              margin: EdgeInsets.only(top: 10, bottom: 20),
              text: "当前余额${widget.totalMoney}元，",
              textSize: 12,
              textWeight: FontWeight.w600,
              textAlignment: Alignment.centerLeft,
              textColor: Colors.grey,
              onChild1Click: () {
                if (double.parse(widget.totalMoney) > 0) {
                  _moneyController.value =
                      TextEditingValue(text: widget.totalMoney);
                }
              },
              child1: Text(
                "全部提现",
                style: TextStyle(
                  fontSize: 12,
                  color: Theme.of(context).accentColor,
                  fontWeight: FontWeight.w600,
                ),
              ),
              child1Alignment: Alignment.centerLeft,
              child1Margin: EdgeInsets.only(left: 96),
            ),
            Container(
              margin: EdgeInsets.only(bottom: 6),
              width: double.infinity,
              height: 40,
              child: RaisedButton(
                onPressed: !btnEnable ? null : _showPwdBoard,
                child: Text("确认提现"),
                disabledTextColor: Color(0XFFBDBDBD),
                textColor: Colors.white,
                disabledColor: Color(0xfff5f5f5),
                color: Theme.of(context).accentColor,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(6),
                ),
              ),
            ),
          ]),
    );
  }

  ///提现说明
  Widget descWidget() {
    String desc = '''
1、钱包金额满100才可提现
2、提现将收取15%的手续费，请悉知！
3、提现申请后将在1到3个工作日内到账,请留意平台消息通知！
''';
    return FSuper(
      margin: EdgeInsets.only(top: 20),
      child1: Text(
        "提现须知",
        style: TextStyle(
          fontSize: 12,
          fontWeight: FontWeight.bold,
          color: Color(0xffE0A23B),
        ),
      ),
      child1Alignment: Alignment.topCenter,
      text: desc,
      textSize: 12,
      textAlign: TextAlign.left,
      textColor: Color(0xffE0A23B),
      padding: EdgeInsets.only(left: 10, right: 10, top: 24),
    );
  }

  ///校验密码
  void _showPwdBoard() {
    String text = _moneyController.text;
    if ("-1".endsWith(payType)) {
      Toast.show("请选择到账账户");
      return;
    }
    if (null == text || text.isEmpty) {
      Toast.show("请输入提现金额");
      return;
    }
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (builder) {
        return CustomKeyboard(
          autoBack: true,
          onClose: () {
            Navigator.pop(context);
          },
          onForget: () {
            Routers.router.navigateTo(context,
                "${Routers.PAGE_CHECKPHONE}?title=bdzf&phone=${user.phone}",
                transition: TransitionType.inFromRight);
          },
          onReset: () {
            Routers.router.navigateTo(context,
                "${Routers.PAGE_CHECKPHONE}?title=xgzf&phone=${user.phone}",
                transition: TransitionType.inFromRight);
          },
          onResult: (data) {
            CancelFunc cancelFunc = Toast.loading("正在校验...");
            String pwd = data.toString().trim();
            Map<String, String> params = Map();
            params["pwd"] = pwd;
            Http.post(Api.URL_WALLET_PWD, params: params,
                successCallBack: (data) {
              Navigator.pop(context);
              cancelFunc();
              _takeCash();
            }, errorCallBack: (error) {
              Navigator.pop(context);
              cancelFunc();
              if ("未设置交易密码" == error) {
                _setPwdDialog();
                return;
              }
              Toast.show(error);
            });
          },
        );
      },
    );
  }

  void _setPwdDialog() {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text("温馨提示"),
            content: Text("您尚未设置交易密码，是否去设置？"),
            actions: <Widget>[
              FlatButton(
                onPressed: () {
                  Navigator.pop(context);
                },
                child: Text("取消"),
              ),
              FlatButton(
                onPressed: () {
                  Navigator.pop(context);
                  if (null != user && null == user.phone) {
                    Toast.show("请先绑定手机号");
                    return;
                  }
                  Routers.router.navigateTo(context,
                      "${Routers.PAGE_CHECKPHONE}?title=bdzf&phone=${user.phone}",
                      transition: TransitionType.inFromRight);
                },
                child: Text("去设置"),
              ),
            ],
          );
        });
  }

  ///提现
  void _takeCash() {
    CancelFunc cancelFunc = Toast.loading("正在提交...");
    Map<String, String> params = Map();
    params["payType"] = payType;
    params["money"] = _moneyController.text;
    Http.post(Api.URL_TRADE_CASH, params: params, successCallBack: (data) {
      cancelFunc();
      applyDialog("您的申请已提交");
    }, errorCallBack: (error) {
      cancelFunc();
      Toast.show(error);
    });
  }

  void applyDialog(String msg) {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text("温馨提示"),
            content: Text(msg),
            actions: <Widget>[
              FlatButton(
                child: Text("知道了"),
                onPressed: () {
                  Navigator.pop(context);
                  Navigator.pop(this.context);
                },
              ),
            ],
          );
        });
  }
}
